package scitc.alumni.util;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;

@Component
public class JwtUtil {
    // 声明过期时间
    @Value("${jwt.expire}")
    private long EXPIRE;
    // 秘钥
    @Value("${jwt.private-key}")
    private String PRIVATE_KEY;

    /**
     * 生成token令牌
     * @param username
     * @param role
     * @return
     */
    public String createToken(String username, String role) {
        SecretKey key = Keys.hmacShaKeyFor(PRIVATE_KEY.getBytes(StandardCharsets.UTF_8));
        Claims claims = Jwts.claims().add("username", username).add("role", role).build();
        Date exp = new Date(System.currentTimeMillis() + EXPIRE);
        JwtBuilder builder = Jwts.builder().signWith(key).claims(claims).expiration(exp);
        return builder.compact();
    }

    /**
     * 获取载荷
     * @param token
     * @return 载荷
     */
    public Claims checkToken(String token) {
        if(token == null || token.isEmpty()){
            return null;
        }
        // 判定token真伪
        try {
            SecretKey key = Keys.hmacShaKeyFor(PRIVATE_KEY.getBytes(StandardCharsets.UTF_8));
            JwtParser jwtParser = Jwts.parser().verifyWith(key).build();
            Jws<Claims> jws = jwtParser.parseSignedClaims(token);
            Claims claims = jws.getPayload();
            return claims;
        }catch( Exception e){
            return  null;
        }
    }
}















